#include<iostream>
#include<string>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<cerrno>

void Usage(const std::string s)
{
    std::cout<<"Usage: ./"<<s<<" server_ip server_port"<<std::endl;
}

int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);

        return 0;
    }

    //1.创建套接字，打开文件
    int sock = socket(AF_INET,SOCK_DGRAM,0);
    if(sock < 0)
    {
        std::cerr<< "socket create faill"<<errno<<std::endl;
        return 1;
    }

    //2.使用服务
    sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(atoi(argv[2]));
    server.sin_addr.s_addr = inet_addr(argv[1]);

    while(1)
    {
        std::string message;
        std::cout << "输入# ";
        std::cin >> message;
        sendto(sock, message.c_str(), message.size(), 0, (struct sockaddr*)&server, sizeof(server));

        sockaddr_in tmp;
        socklen_t len = sizeof(tmp);
        char buff[1024];
        recvfrom(sock,buff,sizeof(buff)-1,0,(sockaddr*)&tmp,&len);
        std::cout<<"Server echo# "<<buff<<std::endl;
    }

    std::cout<<"client"<<std::endl;

    return 0;
}